package cn.tuling.v1;

import java.util.Random;

/**
 * 库存、销售、采购三部分互相依赖
 * 缺陷：
 * 1. 类之间两两依赖，逻辑复杂，编码难度高，若类继续增多，关系网继续复杂，代码将很难维护。
 * 2. 不符合“迪米特法则”：“每个类只和朋友类交流”，这个朋友越少越好，朋友越多，耦合越大。
 */
public class MediatorTest {
    public static void main(String[] args) {
        System.out.println("采购人员采购电脑");
        Purchase purchase = new Purchase();
        purchase.buyIBMComputer(100);

        System.out.println("销售人员销售电脑");
        Sale sale = new Sale();
        sale.sellIBMComputer(sale.getSaleStatus());

        System.out.println("库房管理人员清库处理");
        Stock stock = new Stock();
        stock.clearStock();
    }
}

class Purchase {
    public void buyIBMComputer(int number) {
        Stock stock = new Stock();

        Sale sale = new Sale();

        int saleStatus = sale.getSaleStatus();
        if (saleStatus > 80) {
            System.out.println("采购IBM电脑" + number + "台");
            stock.increaseStock(number);
        } else {
            int buyNumber = number / 2;
            System.out.println("采购IBM电脑" + buyNumber + "台");
            stock.increaseStock(buyNumber);
        }
    }

    public void refuseBuyIBM() {
        System.out.println("不再采购IBM电脑");
    }
}

class Stock {
    private static int COMPUTER_NUMBER = 100;

    public void increaseStock(int number) {
        COMPUTER_NUMBER += number;
        System.out.println("库存数量为：" + COMPUTER_NUMBER);
    }

    public void decreaseStock(int number) {
        COMPUTER_NUMBER -= number;
        System.out.println("库存数量为：" + COMPUTER_NUMBER);
    }

    public int getStockNumber() {
        return COMPUTER_NUMBER;
    }

    public void clearStock() {
        Purchase purchase = new Purchase();

        Sale sale = new Sale();

        System.out.println("清理库存数量:" + COMPUTER_NUMBER);
        sale.offSale();
        purchase.refuseBuyIBM();
    }
}

class Sale {
    public void sellIBMComputer(int number) {
        Stock stock = new Stock();

        Purchase purchase = new Purchase();

        if (stock.getStockNumber() < number) {
            purchase.buyIBMComputer(number);
        }

        System.out.println("销售IBM电脑" + number + "台");
        stock.decreaseStock(number);
    }

    public int getSaleStatus() {
        Random random = new Random(System.currentTimeMillis());
        int i = random.nextInt(100);
        System.out.println("IBM电脑的销售情况为：" + i);
        return i;
    }

    public void offSale() {
        Stock stock = new Stock();
        System.out.println("折价销售IBM电脑" + stock.getStockNumber() + "台");
    }
}
